import 'package:flutter/material.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'dart:async';
import 'package:flutter/services.dart';

class Test7 extends StatefulWidget{
    _TestState createState() => _TestState();
}

class _TestState extends State<Test7> {

    

    String barcode = "";

    @override
    Widget build(BuildContext context) {

        return new Scaffold(
            appBar: AppBar(
                title: Text("扫描二维码"),
                centerTitle: true,
            ),
            body: new Center(
                child: new Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: <Widget>[
                        Padding (
                            padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                            child: Text(barcode, textAlign: TextAlign.center,),
                        ),
                        Container(
                            width: double.infinity,
                            height: 40.0,
                            margin: EdgeInsets.all(40.0),
                            child: FlatButton(
                                color: Color.fromRGBO(81, 126, 219, 1),
                                shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
                                child: Text(
                                    "扫描二维码",
                                    style: TextStyle(color: Colors.white),
                                ),
                                onPressed: scan,
                            )
                        ),
                    ],
                ),
            ),
            
        );
    }


    Future scan() async {
        try {
            String barcode = await BarcodeScanner.scan();
            setState(() {
                return this.barcode = barcode;
            });
        } on PlatformException catch (e) {
            if (e.code == BarcodeScanner.CameraAccessDenied) {
                setState(() {
                return this.barcode = '用户未获取相机权限';
                });
            } else {
                setState(() {
                return this.barcode = 'Unknown error: $e';
                });
            }
        } on FormatException{
            setState(() => this.barcode = '用户点击返回');
        } catch (e) {
            setState(() => this.barcode = 'Unknown error: $e');
        }
    }


}
